package ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.util.LinkedList;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;

import client.ISingleConversation;

public class NickPanel extends JPanel implements INickPanel {

	private static final long serialVersionUID = 0;
	private LinkedList<String> nickList=new LinkedList<String>();
	private LinkedList<JButton> buttonList=new LinkedList<JButton>();
	private ISingleConversation sConversation;
	
	public NickPanel(ISingleConversation sC){
		this.setLayout(new BoxLayout(this,BoxLayout.PAGE_AXIS));
		this.sConversation=sC;
	}
	
	
	public void addNick(String nick){
		if(nickList.contains(nick)){
			
		}else{
			
			nickList.add(nick);
			
			final JButton tempButton = new JButton(nick);
			buttonList.add(tempButton);
			
			tempButton.addActionListener(new ActionListener() {
				
				@Override
				public void actionPerformed(ActionEvent e) {
					startConversation(tempButton.getText());
					
				}
			});
			
			for (Iterator<JButton> iterator = buttonList.iterator() ; iterator.hasNext();) {
				
				JButton button = (JButton) iterator.next();
				this.add(button);
				
			}
				
			
		}
		
		this.repaint();
		this.validate();
				
	}

	@Override
	public void rmNick(String nick) {
		
		
		for (Iterator<JButton> iterator = buttonList.iterator(); iterator.hasNext();) {
			JButton button = iterator.next();
			
			if(button.getText().equalsIgnoreCase(nick)){
				iterator.remove();
			}

		}
		
		this.removeAll();
		this.validate();
		
		for (int i = 0; i < buttonList.size(); i++) {
			this.add(buttonList.get(i));
		}
		
		this.repaint();
		
	}
	

	private void startConversation(String reciever){
		
		sConversation.generateConversation(reciever);
		
	}
}
	

	
